package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {

    @Autowired
    private RestTemplate restTemplate;

    //直接取配置文件
    @Value("tencent.cloud.map")
    private String key;

    /*
     * 计算驾驶路线
     * */
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //请求腾讯的接口，拿到返回结果
        //使用spring提供的调用工具resttemplate实现
        //定义调用地址
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //封装传递的参数
        Map<String,String> map = new HashMap();
        //格式：经度，纬度
        //开始位置
        map.put("from",calculateDrivingLineForm.getStartPointLatitude()+","+calculateDrivingLineForm.getStartPointLongitude());
        //终点位置、
        map.put("to",calculateDrivingLineForm.getEndPointLatitude()+","+calculateDrivingLineForm.getEndPointLongitude());
        //key
        map.put("key",key);
        //使用resttemplate调用 get请求
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);
        //处理返回结果
        int status = result.getIntValue("status");//0：正常 1：异常
        if(status != 0){
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }
        //获取返回的路线
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        //创建返回对象
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        drivingLineVo.setDuration(route.getBigDecimal("duration"));//得到方案预估时间
        drivingLineVo.setDistance(route.getBigDecimal("distance").divideToIntegralValue(new BigDecimal(1000)).setScale(2, RoundingMode.HALF_UP));//方案预估距离 单位：公里，保留两位小数向上取整
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));//路线
        return drivingLineVo;
    }
}
